<template>
    <div>
        <el-card shadow="hover">
            <el-form :inline="true" :model="studentVo" class="demo-form-inline">
                <el-form-item label="学生姓名">
                    <el-input v-model="studentVo.sname" placeholder="学生姓名" size="small"></el-input>
                </el-form-item>
                <el-form-item label="学生住址">
                    <el-input v-model="studentVo.addr" placeholder="学生住址" size="small"></el-input>
                </el-form-item>
                <el-form-item label="所在班级">
                    <el-select v-model="studentVo.cid" placeholder="所在班级" size="small">
                        <el-option label="所有班级" value="0"></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                    <el-button type="primary" @click="search" icon="el-icon-search"  size="small">查询</el-button>
                    <el-button type="success" @click="addUI" icon="el-icon-plus"  size="small">添加学生</el-button>
                    <el-button type="danger" @click="handleDelete" icon="el-icon-delete"  size="small">批量删除</el-button>
                    </el-button-group>
                </el-form-item>
            </el-form>
            <el-divider></el-divider>
            <el-table
                    :data="students"
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        label="学号"
                        prop="sid"
                        align="center"
                        width="80">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        align="center"
                        prop="sname"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="性别"
                        align="center"
                        prop="sex"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="年龄"
                        prop="age"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="住址"
                        prop="addr"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="所在班级"
                        prop="cname"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button-group>
                        <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)">
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)">
                        </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog :title="studForm.sid ? '修改学生' : '添加学生'" :visible.sync="dialogVisible" align="left" :close-on-click-modal="false">
                {{studForm}}
                <el-form :model="studForm" :visible="dialogVisible" :rules="rules" ref="ruleForm">
                    <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                        <el-input v-model="studForm.sname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                        <el-radio-group v-model="studForm.sex">
                            <el-radio label="男" value="男"></el-radio>
                            <el-radio label="女" value="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                        <el-input v-model.number="studForm.age" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="家庭住址" :label-width="formLabelWidth" prop="addr">
                        <el-input v-model="studForm.addr" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                        <el-select v-model="studForm.cid" placeholder="所有班级">
                            <el-option label="所有班级" value="0"></el-option>
                            <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </div>
            </el-dialog>
            <!--分页导航-->
            <el-pagination
                    style="text-align: right;margin-top: 10px;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>

    </div>
</template>

<script>
    export default {
        data() {
                // 自定义验证规则
                const checkAge = (rule, value, callback) => {  // 参1：验证规则 参数2：控件的值 参数3：系统提供的回调
                    if (!value) {
                        return callback(new Error('年龄不能为空'));
                    }else if(!Number.isInteger(value)){
                        return callback(new Error('年龄必须为数字！'));
                    }else{
                        return callback();
                    }
                }
                return {
                    students: [],           // 代表当前的学生列表
                    multipleSelection: [],  // 所选择的学生对象
                    page: 1,                 // 当前页
                    total: 10,               // 总记录数
                    pagesize: 5,             // 每页大小
                    studentVo: {sname: '', addr: ''},           // 条件查询学生对象
                    classes: [],             // 代表班级列表
                    dialogVisible: false,    // 代表对话框显示或隐藏 false: 隐藏 true: 显示
                    formLabelWidth: '120px',
                    studForm: {},            // 代表表单操作的学生对象
                    sids:[],                 // 代表要删除的学生编号
                    rules: {
                        sname: [              // 学生姓名的验证
                            {required: true, message: '学生姓名不能为空!', trigger: blur}
                        ],
                        sex: [               // 学生性别的验证
                            {required: true, message: '必须要选择性别!', trigger: blur}
                        ],
                        age: [
                            // {required: true, message: '学生年龄不能为空!', trigger: blur}
                            {
                                validator: checkAge,trigger:'blur'
                            }
                        ],
                        addr: [
                            {required: true, message: '学生住址不能为空!', trigger: blur}
                        ],
                        cid: [
                            {required: true, message: '选择所在班级!', trigger: blur}
                        ],
                    }
                }
          },
        created() {
                //1. 查询所有学生
                // this.findStudents();
                //2. 分页查询学生列表
                // this.findByPage(this.page,this.pagesize);
                //2. 条件查询带分页
                this.search();
                //3. 查询所有的班级
                this.findClasss();
            },
            methods: {
                //1. 查询所有学生
                findStudents() {
                    this.$axios.get("/student?cmd=list").then(resp => {
                        this.students = resp.data
                    })
                },
                //2. 分页查询学生
                findByPage() {
                    this.$axios.get(`/student?cmd=findByPage&page=${this.page}&pagesize=${this.pagesize}`).then(resp => {
                        this.total = resp.data.total;
                        this.students = resp.data.rows;
                    })
                },
                //3. 查询所有班及
                findClasss() {
                    this.$axios.get("/classes?cmd=list").then(resp => {
                        this.classes = resp.data
                    })
                },
                //4. 条件查询带分页
                search() {
                    //4.1 将json对象转换为字符串
                    let stud = JSON.stringify(this.studentVo);
                    //4.2 向后台发送请求
                    this.$axios.post(`/student?cmd=search&page=${this.page}&pagesize=${this.pagesize}`,
                        "stud=" + stud).then(resp => {
                        this.total = resp.data.total;
                        this.students = resp.data.rows;
                    })
                },
                // 5. 显示添加学生对话框
                addUI() {
                    //5.1 清空表单数据
                    this.studForm = {}
                    // 5.2 打开对话框
                    this.dialogVisible = true
                },
               // 6. 修改学生
                handleEdit(index, row) {
                    console.log(index, row);
                    // 6.1 为studForm赋值
                    this.studForm = row
                    // 6.2 打开对话框
                    this.dialogVisible = true
                },
                // 7. 删除学生
                handleDelete(index, row) {
                    console.log(index, row);
                    //7.1 组织要删除的学生编号
                    //7.1.1 批量删除的情况
                    if(!row){
                        this.sids = this.multipleSelection.map(m=>m.sid);
                    }else{  //7.1.2 单个删除的情况
                        this.sids = [row.sid]
                    }
                    this.$confirm(`此操作将永久删除学生${this.sids}?`, '温馨提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {         // 此处代表点击了"确定"按钮后执行的回调
                        // 7.2 向后台发出删除请求
                        this.$axios.post(`/student?cmd=delete&sids=${this.sids}`).then(resp => {
                           if(resp.data.code == 0){
                               const _this = this
                               this.$message({
                                   type: 'success',
                                   message: resp.data.message,
                                   onClose(){
                                       _this.search()
                                   }
                               });
                           }
                        })
                    })
                },
                //8. 当我们勾选某个学生复选框时触发事件
                handleSelectionChange(val) {
                    this.multipleSelection = val;
                    console.log("multipleSelection:",this.multipleSelection)
                },
                // 9. 提交表单
                submitForm() {
                    this.$refs['ruleForm'].validate((valid) => {
                        //9.1 定义添加或修改的学生的后台地址
                        let url = "/student?cmd=add"
                        if (valid) {            // 只有表单中的所有的控件都验证通过之后，此值才返回true,否则，返回false
                            if(this.studForm.sid){      // 此时修改学生
                                url = "/student?cmd=update"
                            }
                            //9.2 向后台发送请求
                            this.$axios.post(url, "stud=" + JSON.stringify(this.studForm)).then(resp => {
                                console.log("resp:",resp)
                                if(resp.data.code == 0){     // 如果成功，就刷新页面
                                    const _this = this
                                    //9.2.1 关闭当前对话框
                                    this.$message({
                                        message: resp.data.message,
                                        type: 'success',
                                        onClose(){
                                            // ① 关闭对话框刷新列表页面
                                            _this.search();
                                            // ② 关闭对话框
                                            _this.dialogVisible = false
                                        }
                                    });
                                }
                            })
                        } else {
                            console.log('可能有控件验证未通过');
                            return false;
                        }
                    });
                },
                //10. 每页大小改变时触发
                handleSizeChange(val)
                {
                    this.pagesize = val;
                    // this.findByPage()
                    this.search()
                    console.log(`每页 ${val} 条`);
                },
                //11. 当前页改变时触发
                handleCurrentChange(val)
                {
                    this.page = val;
                    // this.findByPage();
                    this.search()
                    console.log(`当前页: ${val}`);
                }
            }
        }
</script>

<style scoped>
    .demo-form-inline {
        text-align: left;
        padding-top: 15px;
        padding-bottom:0;
        margin: 0;

    }
    .el-divider{
        margin: 0;
        padding:0
    }

</style>